#!/usr/bin/env bash

SP_MIN_MEM=512m
SP_MAX_MEM=512m

SCRIPT="$0"
# SCRIPT may be an arbitrarily deep series of symlinks. Loop until we have the concrete path.
while [ -h "$SCRIPT" ] ; do
  ls=`ls -ld "$SCRIPT"`
  # Drop everything prior to ->
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    SCRIPT="$link"
  else
    SCRIPT=`dirname "$SCRIPT"`/"$link"
  fi
done

# some Java parameters
JAVA=`which java 2>/dev/null`
if [[ $JAVA_HOME != "" ]]; then
    JAVA=$JAVA_HOME/bin/java
fi
if test -z "$JAVA"; then
    echo "No java found in the PATH. Please set JAVA_HOME."
    exit 1
fi

APP_HOME=`dirname "$SCRIPT"`/..
export APP_HOME=`cd "$APP_HOME"; pwd`

SP_CLASSPATH=$APP_HOME/conf:$APP_HOME/lib/*

MAIN_CLASS="com.jeecg.modules.JimuReportApplication"
DEF_APP_NAME="jimureport"

#java opts config
SP_OPTS="$JAVA_OPS -Dapp.home=$APP_HOME -Djava.library.path=$APP_HOME/conf"
SP_OPTS="$SP_OPTS -server -Xms${SP_MIN_MEM} -Xmx${SP_MAX_MEM}"

PID_DIR="$APP_HOME/start.d"
PID_NAME="$DEF_APP_NAME.pid"
PID_FILE="$PID_DIR/$PID_NAME"

if [ ! -d "$APP_HOME/logs" ]
then
    mkdir -p $APP_HOME/logs
fi

COMMAND=$1

start(){
  mkdir -p "$PID_DIR"
  if [ -f "$PID_FILE" ]; then
    echo $PID_FILE existsed, pid: `cat $PID_FILE`
    if kill -0 `cat "$PID_FILE"` > /dev/null 2>&1; then
      echo $DEF_APP_NAME running as process `cat $PID_FILE`.  Stop it first.
      exit 1
    fi
  fi
  echo "starting $DEF_APP_NAME ..."
  if $JAVA $SP_OPTS -cp $SP_CLASSPATH $MAIN_CLASS >/dev/null 2>&1 &
  then
    echo $! > "$PID_FILE"
    echo "$DEF_APP_NAME has started! "
    echo "please see the log --> '$APP_HOME/logs/$DEF_APP_NAME.log' or 'ps -ef|grep Application'"
  else
    echo "$DEF_APP_NAME has start Failed"
  fi
}

run(){
  echo "run $DEF_APP_NAME server..."
  $JAVA $SP_OPTS -cp $SP_CLASSPATH $MAIN_CLASS
}

stop(){
  if [ -f "$PID_FILE" ]; then
    if kill `cat $PID_FILE` > /dev/null 2>&1; then
      echo "stop $DEF_APP_NAME ..."
      kill `cat $PID_FILE`
  		rm $PID_FILE
    else
      rm $PID_FILE
      echo No $DEF_APP_NAME to stop
    fi
  else
    echo "stop $DEF_APP_NAME ..."
    warningpid=`jps -l|grep $MAIN_CLASS | cut -f 1 -d " "`
    echo "$MAIN_CLASS process's pid is $warningpid"

    if [ $warningpid ]
      then
        jps -l|grep $MAIN_CLASS | cut -f 1 -d " " |xargs  kill -15
        echo "$MAIN_CLASS [$warningpid] is stoped!"
      else
        echo "$MAIN_CLASS stop failed!"
    fi
  fi
}

status(){
  warningpid=`jps -l|grep $MAIN_CLASS | cut -f 1 -d " "`
  if [ $warningpid ]
  then
    echo "$MAIN_CLASS [$warningpid] is running "
  else
    echo "$MAIN_CLASS is not running"
  fi
}

docommand() {
  case "$COMMAND" in
    'start')
      start
      ;;
    'run')
      run
      ;;

    'stop')
      stop
      ;;

    'restart')
      stop;
      sleep 5
      start;
      ;;

    'status')
      status
      ;;

		*)
		  echo "usage: [start|run|stop|restart|status|log]"
		;;
  esac
}
docommand "$@"
exit 0